const path = require('path')
const {
  prompt
} = require('inquirer')
const message = require('../lib/message')
const download = require('download-git-repo')
const ora = require('ora')
const fs = require('fs')
const templates = require('../templates')
const question = [{
  type: 'input',
  name: 'name',
  message: 'project name：',
  validate(val) {
    const validate = !!val.trim() && (val.trim().split(" ")).length === 1;
    return validate || 'project name is not allowed to have spaces.';
  },
  filter(val) {
    return val.trim()
  }
}]
const question2 = [{
    type: 'input',
    name: 'description',
    message: 'project description：'
  },
  {
    type: 'list',
    name: 'template',
    message: 'which template?',
    choices: [],
    default: 'uni'
  }
]

async function init() {
  // 项目名称
  const {
    name: projectName
  } = await prompt(question)
  const rootName = path.basename(process.cwd()) // 当前目录
  const list = fs.readdirSync(process.cwd()) // 当前目录列表
  try {
    if (list.length) {
      // 目录不为空，且存在于projectName同名目录，提示已存在，结束
      let isExist = list.some(name => {
        const fileName = path.join(process.cwd(), name)
        const isDir = fs.statSync(fileName).isDirectory()
        return name === projectName && isDir
      })
      if (isExist) {
        message.error(`项目${projectName}已存在`)
        process.exit()
      }
    }
  } catch (err) {
    message.error(err)
    process.exit()
  }
  create(projectName)
};

async function create(projectName) {
  try {
    for (const i of question2) {
      if (i.name === 'template') {
        i.choices = Object.keys(templates)
      }
    }
    const {
      description,
      template
    } = await prompt(question2)
    const gitPlace = templates[template].path

    const spinner = ora('Downloading please wait...');

    spinner.start();
    // 非GitHub, GitLab, Bitbucket的仓库使用clone
    download(`${gitPlace}`, `./${projectName}`, {
      clone: gitPlace.includes('uni')
    }, (err) => {
      if (err) {
        message.error(err)
        process.exit()
      }

      fs.readFile(`./${projectName}/package.json`, 'utf8', function(err, data) {
        if (err) {
          spinner.stop();
          message.error(err)
          return;
        }

        const packageJson = JSON.parse(data);
        packageJson.name = projectName;
        packageJson.description = description;

        fs.writeFile(`./${projectName}/package.json`, JSON.stringify(packageJson, null, 2), 'utf8', function(
          err) {
          if (err) {
            spinner.stop();
            message.error(err)
          } else {
            spinner.stop();
            message.success('project init successfully!')
            message.info(
              `${`cd ${projectName}`}
${'npm install'}
${`npm run ${gitPlace.includes('wepy') ? 'dev' : 'serve'}`}
            `
            );
          }
        });
      });
    })

  } catch (err) {
    message.error(err)
    process.exit()
  }
}
init()
